import serial
from threading import Thread, Event
import threading
import sys, traceback
import asyncore
import struct

from time import sleep
def crc16str(s):
    crc = 0xffff
    for index1 in range(len(s)):
        x = ord(s[index1])
        temp = x & 0x00FF;
        crc = crc ^ temp;
        for index2 in range(1, 9):
            if crc & 0x0001 != 0:
                crc = (((crc >> 1) ^ 0xA001)) & 0xffff
            else:
                crc = (crc >> 1) & 0xffff
    crc=crc & 0xFFFF
    h=crc<<8&0xff00
    l=crc>>8&0x00ff
    crc=h+l
    return crc
device = serial.Serial(port="/dev/ttyTX0",baudrate=115200,
    bytesize=serial.EIGHTBITS, parity=serial.PARITY_NONE,
    stopbits=serial.STOPBITS_ONE, timeout=0.5,
    xonxoff=0, rtscts=0 )

while True:
    s=device.read(1024)
    print repr(s)
    result=''
    if len(s)>1:
        if s[12]=='\x0A':
            dataSeg=''
            result += '\x55\xAA'
            result += '\x0C'
            dataSeg += s[4:6]
            dataSeg += '\x00\x26\xFF\xFF\x00\x01\x21\x55\x00\x02'
            result += dataSeg
            
            crc=crc16str(dataSeg)
            
            result+=struct.pack(">H",crc)
            result+='\x13\x10'
            device.write(result)
            
            sleep(1)
            result=''
            
            
            result += '\x55\xAA'
            dataSeg=''
            dataSeg += s[4:6]
            
            dataSeg += '\x00\x29\xFF\xFF\x00\x01\x22\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\x00\x02'
            dataSeg += '\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF'
            
            
            length=len(dataSeg)
                
            crc=crc16str(dataSeg)
            result+=struct.pack(">H",int(length))
                
            result+=dataSeg
            result+=struct.pack(">H",crc)
            result+='\x13\x10'
            device.write(result)